# coding=utf-8

import os
import json
import time
import pathlib
from command import base

from command.component import Component
from . import common


EN_DATA = os.environ['HOME'] + '/.en_data'
DATA_FILE = EN_DATA + "/en.data";

## 装在所有组件的封装类
ALL_COMPONENTS = {};


## 查询en的数据，一般存储已安装组件，或其他一些信息，结构如下
# {
#     "components": {
#         # 组件
#         "redis": {
#             # 安装时间
#             "install_time": "2023/11/23 08:22:33"
#         }
#     },
# }


def init_en_data():
    if os.path.isdir(EN_DATA):
        return;
    en_data = pathlib.Path(EN_DATA)
    en_data.mkdir(parents=True)


def get_common_data():
    init_en_data()
    common_data = {};
    if not os.path.isfile(DATA_FILE):
        with open(DATA_FILE, "w") as file:
            file.write("{}")
        common_data = {}
        return common_data;
    filedata = ""
    with open(DATA_FILE, "r") as file:
        filedata = file.read()
    if common.LOG:
        print(f"DATA_FILE 内容为 : {filedata}")
    common_data = json.loads(filedata)
    return common_data;




## 是否已安装某组件
def is_install(component):
    init_en_data()
    data = get_common_data();
    if not data.__contains__("components"):
        return False
    components = data.get("components")
    if not components.__contains__(component):
        return False
    return True


## 执行安装
def run_install(component, rVersion = None):
    init_en_data()
    com : Component = ALL_COMPONENTS[component]
    if com.check():
        notify_install(component, rVersion)
        return;
    child_coms = com.dependencies()
    # 如果安装的是会务 且 主版本为S16 则加装fileview
    if rVersion and "S16" in rVersion and component == "venus":
        child_coms.append("fileview")
    for c in child_coms:

        if not is_install(c):
            run_install(c)

        if c == 'docker':
            if not is_docker_running():
                print("docker未启动，无法安装，请执行 'sudo service docker start' 启动docker")
                return;
    if com.install(rVersion=rVersion):
        notify_install(component, rVersion)



## 执行更新
def run_update(component, rVersion = None):
    init_en_data()
    com = ALL_COMPONENTS[component]
    data = get_common_data();

    if not data.__contains__("components"):
        data['components'] = {};
    components = data.get("components")
    if not components.__contains__(component):
        print(f"{component}未安装，无法执行更新操作")
        return
    com_obj : dict = components[component]
    if rVersion is None:
        rVersion = 'latest' if not com_obj.__contains__('rVersion') else com_obj['rVersion'];

    child_coms = com.dependencies()
    for c in child_coms:
        if c == 'docker':
            if not is_docker_running():
                print("docker未启动，无法安装，请执行 'sudo service docker start' 启动docker")
                return;
    if com.update(rVersion=rVersion):
        notify_update(component, rVersion)

def get_version(component):
    init_en_data()
    data = get_common_data()
    if not data.__contains__("components"):
        data['components'] = {}
    components = data.get("components")
    if components.__contains__(component):
        return components[component]['rVersion']

## 执行卸载
def run_uninstall(component):
    init_en_data()
    com : Component = ALL_COMPONENTS[component]
    child_coms = com.dependencies()
    for c in child_coms:
        if c == 'docker':
            if not is_docker_running():
                print("docker未启动，无法安装，请执行 'sudo service docker start' 启动docker")
                return;
    # for coms in ALL_COMPONENTS.keys():
    #     parent_coms : Component = ALL_COMPONENTS[coms]
    #     if component in parent_coms.dependencies():
    #         if parent_coms.check():
    #             parent_coms.uninstall();
    if com.check():
        com.uninstall()
    notify_uninstall(component)



## 标记某个组件已安装
def notify_install(component, rVersion):
    '''
    component : 组件对象

    rVersion  ：指定安装的版本

    '''
    init_en_data()
    data = get_common_data();
    if not data.__contains__("components"):
        data['components'] = {};
    components = data.get("components")
    if components.__contains__(component):
        return
    components[component] = {}
    components[component]['install_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    components[component]['rVersion'] = rVersion;
    json_str = json.dumps(data);
    with open(DATA_FILE, "w") as file:
        file.write(json_str)


def notify_update(component, rVersion):
    '''
    修改组件记录的版本号
    component : 组件对象
    rVersion  ：指定安装的版本
    '''
    data = get_common_data();
    if not data.__contains__("components"):
        return ;
    components = data.get("components")
    if components.__contains__(component):
        components[component]['install_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        components[component]['rVersion'] = rVersion;
        json_str = json.dumps(data);
        with open(DATA_FILE, "w") as file:
            file.write(json_str)

def is_docker_running():
    '''
    查看docker是否在运行
    '''
    content = base.cmd_with_content("systemctl", ["is-active", "docker"]);
    if content == 'active':
        return True
    content = base.cmd_with_content('snap', ['services', 'docker.dockerd']);
    if content.__contains__('docker.dockerd  enabled  active'):
        return True;
    return False


## 标记某个组件已卸载
def notify_uninstall(component):
    init_en_data()
    data = get_common_data();
    if not data.__contains__("components"):
        data['components'] = {};
    components = data.get("components")
    if components.__contains__(component):
        components.pop(component)
    json_str = json.dumps(data);
    with open(DATA_FILE, "w") as file:
        file.write(json_str)